package collector

import (
	"database/sql"
	"log/slog"

	"github.com/prometheus/client_golang/prometheus"
)

const (
	// Scrape query.
	jobsQuery = `select count(*) from sysjob.sysjobhistories2 where errcode !=0`

	// Subsystem.
	jobs = "jobs"
)

var (
	jobsDesc = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, jobs, "err_job"),
		"The jobs in the DM",
		nil, nil,
	)
)

type Jobs struct {
}

func (Jobs) Name() string {
	return "jobs"
}
func (Jobs) Scrape(db *sql.DB, ch chan<- prometheus.Metric, backupPath string, logger *slog.Logger) error {

	var (
		jobs float64
	)
	jobsRows, err := db.Query(jobsQuery)
	if err != nil {
		logger.Error("Failed to query jobs", "error", err)
		return err
	}
	defer jobsRows.Close()
	for jobsRows.Next() {
		if err := jobsRows.Scan(&jobs); err != nil {
			logger.Error("Failed to scan jobs row", "error", err)
			return err
		}
		ch <- prometheus.MustNewConstMetric(
			jobsDesc, prometheus.GaugeValue, jobs,
		)
	}

	return nil
}

func init() {
	RegisterScraper("jobs", Jobs{})
}

var _ Scraper = Jobs{}
